﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.Configuration;
using System.Web.Hosting;

namespace Akronus.TaskScheduler
{
    /// <summary>
    /// Sends a request to the application that is specified in the configuration file.
    /// </summary>
    public class KeepAliveTask : TaskBase
    {
        protected string testUrl;

        /// <summary>
        /// Executes the task.
        /// </summary>
        public override void Execute()
        {
            Uri targetUri = null;

            if (Uri.IsWellFormedUriString(testUrl, UriKind.Relative))
            {
                var appUri = new Uri(this.ApplicationUrl);
                targetUri = new Uri(appUri, testUrl);
            }
            else if (Uri.IsWellFormedUriString(testUrl, UriKind.Absolute))
            {
                targetUri = new Uri(testUrl);
            }
            else
            {
                TaskLog.Add(string.Format(" The url '{0}' which is specified for '{1}' task is not correct. It is allowed to specify the relative path to the page or full url.", testUrl, Name), LogPriority.High);
            }

            if (targetUri != null)
            {

                WebRequest request = WebRequest.Create(targetUri);
                request.Timeout = 0;
                try
                {
                    request.GetResponse();
                }
                catch (WebException)
                {

                }
            }
        }

        /// <summary>
        /// Reads configuration.
        /// </summary>
        public override void Initialize()
        {
            testUrl = Configuration.Attributes.GetAttributeValue("testURL");
            string fullUrl = Configuration.Attributes.GetAttributeValue("fullURL", string.Empty);

            if (!string.IsNullOrEmpty(fullUrl))
                testUrl = fullUrl;
        }
    }
}
